//
//  PostServer.m
//  CYWFrame
//
//  Created by Macx on 2017/8/4.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PostServer.h"
#import <AFNetworking.h>
#import <MBProgressHUD.h>
#import "UIView+LZCView.h"

@implementation PostServer


+ (void)postsImage:(NSMutableArray *)mArr video:(NSString* )videoPath text:(NSString *)text goodId:(NSString *)goodId questionId:(NSString *)questionId questionParam:(NSDictionary *)questionParam topic:(NSString *)topic order_id:(NSString *) order_id{
    
    UIViewController *currVC = [[[UIView alloc] init] topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
//    [MBProgressHUD showHUDAddedTo:currVC.view animated:YES];
    AFHTTPSessionManager *afn = [AFHTTPSessionManager manager];
    
    // 请求头
    [afn.requestSerializer setValue:[GetUserDefaule(Token) valueForKey:@"access_token"]forHTTPHeaderField:@"Authorization"];
    
    if (mArr.count == 0 && videoPath.length == 0) {
        NSDictionary *postParam;
        NSString *url;
        if (!goodId && !questionId) {
            postParam = @{@"details":text,
                          @"type":@"1",
                          @"tag":topic};
            url = APIPosts;
            
        }
        else {
            if (goodId.length > 0) {
                NSLog(@"i am here to comment1，good ID is %@", goodId);
                postParam = @{
                              @"body":text,
                              @"order_id":order_id,
                              };
                url = [NSString stringWithFormat:@"%@/%@/comments", APIMallsGoods, goodId];
            }
            else {
                postParam = @{@"body":text};
                if (questionParam) {
                    postParam = @{@"body":text,
                                  @"type":questionParam[@"type"],
                                  @"amount":questionParam[@"amount"]};
                }
                url = [NSString stringWithFormat:@"%@/%@/answers", APIQuestions, questionId];
                
            }
            
        }
        
        [[NetworkTool sharedTool] requestWithName:@"发布图文帖子" URLString:url parameters:postParam method:@"POST" callBack:^(id responseObject) {
            
//            [MBProgressHUD hideHUDForView:currVC.view animated:YES];
            
            [currVC dismissViewControllerAnimated:YES completion:nil];
            
        }];
    }
    
    else if (videoPath.length > 0) {
        
        NSLog(@"视频 paht = %@", videoPath);
        
        NSDictionary *dict = @{
                               @"video":@""
                               };
        
        [MBProgressHUD showHUDAddedTo :currVC.view animated:YES];
        
        [afn POST:APIMicrovideos parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:videoPath] name:@"video" fileName:[videoPath lastPathComponent] mimeType:@"video" error:nil];
            // 工程里的视频
//            [formData appendPartWithFileURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:videoPath ofType:nil]] name:@"file" fileName:@"video" mimeType:@"video/mp4" error:nil];
            
            } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
            id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
            NSString *path = [[[obj valueForKey:@"payload"] valueForKey:@"data"] valueForKey:@"video"];
            NSLog(@"上传视频 success = %@", path);
            
            NSDictionary *postParam = @{@"details":text,
                                        @"video":path ,
                                        @"type":@"2",
                                        @"tag":topic};
            
            [MBProgressHUD hideHUDForView:currVC.view animated:YES];
                
            [[NetworkTool sharedTool] requestWithName:@"发布图文帖子" URLString:APIPosts parameters:postParam method:@"POST" callBack:^(id responseObject) {
                
                [currVC dismissViewControllerAnimated:YES completion:nil];
                
            }];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"上传视频 failure = %@", error);
//            [MBProgressHUD hideHUDForView:currVC.view animated:YES];
            [currVC presentViewController:[self AFNErrorAlert:error] animated:YES completion:nil];
        }];

    }
    
    else {
    
        NSDictionary *dict = @{
                               @"file[]":@[]
                               };
        
        [afn POST:APIImages parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            // formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
            // 这里的_photoArr是你存放图片的数组
            for (int i = 0; i < mArr.count; i++) {
                
                UIImage *image = mArr[i];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
                
                // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
                // 要解决此问题，
                // 可以在上传时使用当前的系统事件作为文件名
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                // 设置时间格式
                [formatter setDateFormat:@"yyyyMMddHHmmss"];
                NSString *dateString = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
                /*
                 *该方法的参数
                 1. appendPartWithFileData：要上传的照片[二进制流]
                 2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
                 3. fileName：要保存在服务器上的文件名
                 4. mimeType：上传的文件的类型
                 */
                [formData appendPartWithFileData:imageData name:@"pic[]" fileName:fileName mimeType:@"image/jpeg"]; //
            }
        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
            NSArray *imgArr = [[[obj valueForKey:@"payload"] valueForKey:@"data"] valueForKey:@"images"];
            NSLog(@"上传图片 success = %@", imgArr);

            NSString *imgStr = [imgArr componentsJoinedByString:@","];
            
            NSDictionary *postParam;
            NSString *url;
            if (!goodId && !questionId) {
                postParam = @{@"details":text,
                              @"pic":imgStr,
                              @"type":@"1"};
                url = APIPosts;
            }
            
            else {
                NSLog(@"i am here to comment2，good ID is %@", goodId);
                if ([goodId length] > 0) {
                    NSLog(@"i am here to comment2");
                    postParam = @{@"pics":imgStr,
                                  @"body":text,
                                  @"order_id":order_id
                                  };
                    url = [NSString stringWithFormat:@"%@/%@/comments", APIMallsGoods, goodId];
                }
                else {
                    postParam = @{@"pics":imgStr,
                                  @"body":text};
                    if (questionParam) {
                        postParam = @{@"pics":imgStr,
                                      @"body":text,
                                      @"type":questionParam[@"type"],
                                      @"amount":questionParam[@"amount"]};
                    }
                    url = [NSString stringWithFormat:@"%@/%@/answers", APIQuestions, questionId];
                }
                
            }
            
            [[NetworkTool sharedTool] requestWithName:@"发布图文帖子" URLString:url parameters:postParam method:@"POST" callBack:^(id responseObject) {
                
                [currVC dismissViewControllerAnimated:YES completion:nil];
//                [MBProgressHUD hideHUDForView:currVC.view animated:YES];
                
            }];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"上传图片 failure = %@", error);
//            [MBProgressHUD hideHUDForView:currVC.view animated:YES];
            [currVC presentViewController:[self AFNErrorAlert:error] animated:YES completion:nil];
        }];
    }
    
}


+ (UIAlertController *)AFNErrorAlert:(NSError *)error {
    
    UIViewController *currVC = [[[UIView alloc] init] topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    [MBProgressHUD hideHUDForView:currVC.view animated:YES];
    
    NSString *message;
    
    if (error.code == -1009 || error.code == -1001 || error.code == -1005) {
        message = @"请检查网络状况";
    }
    else {
        NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
        
        NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];NSLog(@"error--%@", serializedData);
        message = serializedData[@"message"];
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    return alert;
}


@end
